package com.elm.mapper;

import com.elm.po.Wallet;
import com.elm.po.Transaction;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface WalletMapper {

    //根据用户id查询钱包
    @Select("SELECT * FROM wallet WHERE user_id = #{userId}")
    Wallet getWalletByUserId(int userId);

    //创建钱包
    @Insert("INSERT INTO wallet(user_id, balance, frozen, overdraft) VALUES(#{userId}, 0, 0, 0)")
    int createWallet(int userId);

    //充值
    @Update("UPDATE wallet SET balance = balance + #{amount} WHERE user_id = #{userId}")
    int recharge(int userId, Double amount);

    //提现
    @Update("UPDATE wallet SET balance = balance - #{amount} WHERE user_id = #{userId}")
    int withdraw(int userId, Double amount);

    //减少透支金额
    @Update("UPDATE wallet SET overdraft = overdraft - #{amount} WHERE user_id = #{userId}")
    int reduceOverdraft(int userId, Double amount);

    //根据walletId查询所有流水
    @Select("SELECT * FROM transaction WHERE to_id = #{walletId} or from_id = #{walletId} ORDER BY create_time DESC")
    List<Transaction> getTransactions(int walletId);

    //1. 增加冻结金额
    @Update("UPDATE wallet SET frozen = frozen + #{amount} WHERE id = #{walletId}")
    int addFrozen_balance(int walletId,double amount);

    //2. 修改金额相关的统一方法
    @Insert("INSERT INTO transaction(from_id,to_id,aggregate_amount,balance_amount,overdraft_amount,txn_type,remark,order_id) VALUES(#{from_id},#{to_id},#{balanceAmount}+#{overdraftAmount},#{balanceAmount},#{overdraftAmount},#{type},#{remark},#{orderId})")
    int insertTransaction(int orderId,int from_id, int to_id,Double balanceAmount,Double overdraftAmount,String type,  String remark);

    @Update("UPDATE wallet SET balance = balance + #{balanceAmount}, overdraft = overdraft + #{overdraftAmount} WHERE user_id = #{customer_id}")
    int increaseBalance(@Param("customer_id") int customerId, @Param("balanceAmount") double balanceAmount, @Param("overdraftAmount") double overdraftAmount);


    //3. 修改vip等级
    @Update("UPDATE wallet SET vip = #{vip_level} WHERE id = #{walletId}")
    int updateVip(int walletId,int vip_level);

    //4. 更新消费总额
    @Update("UPDATE wallet SET consumption = consumption + #{amount} WHERE id = #{walletId}")
    int addConsumption(int walletId,double amount);

    //5. 拿userid查wallet类
    @Select("SELECT id FROM wallet WHERE user_id = #{userId}")
    int getWalletIdByUserId(int userId);

    //6. 拿orderid查Transaction
    @Select("SELECT * FROM transaction WHERE order_id = #{orderId}")
    Transaction getTransactionByOrder(int orderId);


    // 更新整个钱包信息
    @Update("UPDATE wallet SET balance = #{balance}, frozen = #{frozen}, overdraft = #{overdraft}, " +
            "consumption = #{consumption}, vip = #{vip}, updated_at = NOW() WHERE id = #{id}")
    int updateWallet(Wallet wallet);

}
